import { defineStore } from 'pinia'
import { reactive, ref } from 'vue'

export const useAuthUserStore = defineStore(
  'authUser',
  () => {
    const token = ref('')
    const userInfo = ref<any>({
      username: '',
      roles: [],
      extra: [],
    })
    const userMenus = ref<any>([])
    //当前的页面菜单
    const activeMenu = reactive({
      selectedKey: '',
      openKey: '',
    })
    const saveData = (data: any) => {
      token.value = data.token
      userInfo.value.username = data.userInfo.username
      userInfo.value.email = data.userInfo.email
      userInfo.value.roles = data.userInfo.roles
      userInfo.value.extra = data.userInfo.extra
      userMenus.value = data.userInfo.menus
    }
    const clearData = () => {
      userInfo.value.username = ''
      userInfo.value.email = ''
      userInfo.value.roles = []
      userInfo.value.extra = []
      token.value = ''
      userMenus.value = []
      Object.assign(activeMenu, { selectedKey: '', openKey: '' })
    }

    const updateActiveMenu = (menu: { selectedKey: string; openKey: string }) => {
      // console.log('更新menu', menu)
      Object.assign(activeMenu, menu)
    }

    return { token, userInfo, userMenus, saveData, clearData, updateActiveMenu, activeMenu }
  },
  {
    persist: true,
  }
)

// State:保存登录用户的信息，如用户名、用户ID,用户角色，用户权限列表
// getters：检查用户权限
// action：登录与登出的token令牌操作
